/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.noah.service;

import com.noah.model.UserModel;
import com.noah.rowmapper.UserRowMapper;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 *
 * @author ngoc.phan
 */
public class UserService {

    private JdbcTemplate jdbcTemplate;

    /**
     * @return the jdbcTemplate
     */
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    /**
     * @param jdbcTemplate the jdbcTemplate to set
     */
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    /*
     * check login
     */
    public boolean checkLogin(String username, String password) {
        boolean flag = false;
        String sql = "SELECT * FROM user WHERE userName=? AND password=?";
        if (getJdbcTemplate().query(sql, new Object[]{username, password}, new UserRowMapper(jdbcTemplate)).size() == 1) {
            flag = true;
        } else {
            flag = false;
        }
        return flag;
    }
    /*
     * List all user
     */
    public List<UserModel> viewUser(){
        String sql = "Select * from user";//"Select * from user inner join role on user.RoleId = role.RoleId";
        return getJdbcTemplate().query(sql,new UserRowMapper(jdbcTemplate));
    }
    /*
     * insert new user
     */
    public void insertUser(UserModel user){
        String sql = "insert into user(userName,password,roleId) values(?,?,?)";   
        this.getJdbcTemplate().update(sql, new Object[]{user.getUserName(),user.getPassword(),user.getRole().getRoleId()});
    }
    /*
     * Searching user
     */
     public List<UserModel> viewUserByName(String userName){
        String sql = "select * from user where userName like '%"+userName+"%'";//"Select * from user inner join role on user.RoleId = role.RoleId";
        return getJdbcTemplate().query(sql,new UserRowMapper(jdbcTemplate));
    }
    
    /*
     * update user
     */
     public void updateUser(UserModel user){
         String sql = "update user set userName=?,password=? where userId = ?";
         getJdbcTemplate().update(sql,new Object[]{user.getUserName(),user.getPassword(),user.getUserId()});
     }
}
